﻿using System;
using System.Linq;
using DotNETStack.Core.Data;
using DotNETStack.Core.Model;
using DotNETStack.LinqToSqlDataProvider.Model;

namespace DotNETStack.LinqToSqlDataProvider.Data
{
    public class UserRepository : IUserRepository
    {
        #region Private Properties

        private DotNETStackDbDataContext Context { get; set; }

        #endregion

        #region Constructors

        public UserRepository(DotNETStackDbDataContext context)
        {
            Context = context;
        }

        #endregion

        #region Public Methods

        public IUser GetByEmail(String email)
        {
            return Context.dns_Users.WithEmail(email).SingleOrDefault();
        }

        public Boolean IsValidUser(String email, String password)
        {
            IQueryable<dns_User> q = Context.dns_Users.WithEmail(email).WithPassword(password);
            return q.SingleOrDefault() != null;
        }

        public Boolean UserExists(String email)
        {
            return Context.dns_Users.WithEmail(email).SingleOrDefault() != null;
        }

        public Boolean CreateUser(String userName, String email, String password)
        {
            if (UserExists(email))
                return false;

            var user = new dns_User
                           {
                               Email = email,
                               CreationDate = DateTime.Now,
                               ModificationDate = DateTime.Now,
                               Name = userName,
                               Password = password
                           };
            try
            {
                Context.dns_Users.InsertOnSubmit(user);
                Context.SubmitChanges();
                return true;
            }
            catch
            {
                return true;
            }
        }

        #endregion
    }
}